<?php

class Corporate {

//    protected $corporateNodeType;  // Liste des type de noeud
    protected $corporateTree;      // Arborescence du compte
    protected $corporateTreeUser;  // Arborescence du user connecté
    protected $corporateTreeTmp;   // Arborescence temporaire pour une éventuelle utilisation temporaire
    protected $db_name;

    //============================================================================
    // __construct
    //============================================================================

    public function __construct($db_name) {
        try {
            $this->db_name = $db_name;
            $this->hydrate();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // hydrate
    //============================================================================
    public function hydrate() {
        GLOBAL $REQUEST_019, $REQUEST_020;
        try {
//            $this->corporateNodeType = db_request_select($REQUEST_020, [], $this->db_name);
            $this->corporateTree = db_request_select($REQUEST_019, [], $this->db_name);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // get_list_node_child
    // fonction qui récupère (incluant le node en param d'entrée les noeuds enfants
    //============================================================================
    public function get_list_node_child($id_node, $id_mode = 0) {
        try {
            $index = 0;

            // je copie le premier noeud dans le tableau résultat
            for ($inc = 0, $stop = (count($this->corporateTree) - 1); $inc < $stop; $inc++) {
                if ($id_node == (int) $this->corporateTree[$inc][0]) {
                    $this->corporateTreeUser[0][0] = $this->corporateTree[$inc][0];
                    $this->corporateTreeUser[0][1] = $this->corporateTree[$inc][1];
                    $this->corporateTreeUser[0][2] = $this->corporateTree[$inc][2];
                    $this->corporateTreeUser[0][3] = $this->corporateTree[$inc][3];
                    $index++;
                }
            }
            // Si le noeud existe alors on parse pour trouver ses enfants
            if ($index > 0) {
                for ($inc = 0, $stop = (count($this->corporateTree) - 1); $inc < $stop; $inc++) {
                    if ($id_node == (int) $this->corporateTree[$inc][3]) {
                        $this->corporateTreeUser[$index][0] = $this->corporateTree[$inc][0];
                        $this->corporateTreeUser[$index][1] = $this->corporateTree[$inc][1];
                        $this->corporateTreeUser[$index][2] = $this->corporateTree[$inc][2];
                        $this->corporateTreeUser[$index][3] = $this->corporateTree[$inc][3];
                        $index++;
                        $index = $this->get_list_next_node_child($this->corporateTree[$inc][0], $index);
                    }
                }
            }
            return $this->corporateTreeUser;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    protected function get_list_next_node_child($id_node, $index) {
        try {
            for ($inc2 = 0, $stop2 = (count($this->corporateTree) - 1); $inc2 < $stop2; $inc2++) {
                if ($id_node == (int) $this->corporateTree[$inc2][3]) {
                    $this->corporateTreeUser[$index][0] = $this->corporateTree[$inc2][0];
                    $this->corporateTreeUser[$index][1] = $this->corporateTree[$inc2][1];
                    $this->corporateTreeUser[$index][2] = $this->corporateTree[$inc2][2];
                    $this->corporateTreeUser[$index][3] = $this->corporateTree[$inc2][3];
                    $index++;
                    $index = $this->get_list_next_node_child($this->corporateTree[$inc2][0], $index);
                }
            }
            return $index;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // get_list_service
    //============================================================================
    public function get_list_service() {
        global $REQUEST_021;
        /*
         * Obtient les noeuds de type "Service" uniquement ( adm_client_arborescence.type = 40 )
         */
        return db_request_select($REQUEST_021, NULL, $this->db_name);
    }

    //============================================================================
    // get_list_node
    // fonction aussi présente dans l'objet User
    //============================================================================
    public function get_list_node($param_db_name = NULL, $id_noeud = NULL) {
        GLOBAL $REQUEST_028;

        try {
            $data = NULL;
            if ($id_noeud == NULL) {
                // Je récupère la liste des noeuds
                $data = db_request_select($REQUEST_028, NULL, ($param_db_name == NULL) ? $this->db_name : $param_db_name);
            } else {
                // A CODER
                // Je récupère la liste des noeuds sans les noeuds enfants de l'id_noeud passé en param
                //$tab_arg = array(':id_noeud' => $tab_arg[':id_noeud']);
                //$data = db_request_select($REQUEST_0XX,$tab_arg,($param_db_name==NULL)?$this->db_name:$param_db_name);
                $data = db_request_select($REQUEST_028, NULL, ($param_db_name == NULL) ? $this->db_name : $param_db_name); // en attendant...
            }
            return $data;
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // get_list_type_node
    //============================================================================
    public function get_list_type_node() {
        GLOBAL $REQUEST_020;

        try {
            // Je récupère la liste des services
            return db_request_select($REQUEST_020, NULL, $this->db_name);
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //======================================================f======================
    // create_corporate_node()
    //============================================================================
    public function create_corporate_node($tab_arg, $db_name = NULL) {
        GLOBAL $REQUEST_022;
        try {
            if ($db_name == NULL)
                $db_name = $this->db_name;

            db_request_insert($REQUEST_022, $tab_arg, $db_name);
            $this->hydrate();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // update_corporate_node()
    //============================================================================
    public function update_corporate_node($tab_arg) {

        GLOBAL $REQUEST_023;

        try {
            db_request_update($REQUEST_023, $tab_arg, $this->db_name);
            $this->hydrate();
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // delete_corporate_node
    //============================================================================
    public function delete_corporate_node($tab_arg) {
        GLOBAL $REQUEST_024;
        try {
            //Avant toutes chose on doit vérifier que ce noeud n'est pas utiliser dans la base de données du client.
            //************************


            db_request_delete($REQUEST_024, $tab_arg, $this->db_name);
            $this->hydrate();
//        } catch (SIRHException $e) {
//            throw new SIRHException($e->getMessage());
        } catch (Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    //============================================================================
    // show_form_corporate
    //============================================================================
    public function show_form_corporate_update($id, $db) {
        global $REQUEST_042, $LABEL_0060, $LABEL_0061;

        $data = db_request_select($REQUEST_042, [':id_noeud' => $id], $db);

        // Update form

        echo gui_form_post_open("corporate_update", RenderUrl('nodes/update?node=list'));

        echo gui_form_input_hidden_field("id_noeud", $data[0][0]);

        echo gui_table_tag_open("100%", 0, 5, 0, NULL, NULL, NULL);

        $dataNode = $this->get_list_node(NULL, $data[0][0]);
        $tabTmp = array(0, Strings::LABEL_0062);
        array_unshift($dataNode, $tabTmp);
        $string_data = gui_form_select_field("noeud_parent_update", "noeud_parent_update", $dataNode, $data[0][4], true, "", 0);

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"noeud_parent\">" . $LABEL_0061 . "</label>");
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        $string_data = gui_form_input_text_field("designation_update", $data[0][1], 50, 255, "designation_update", true, false);

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"designation\">" . $LABEL_0060 . "</label>");
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        $dataService = $this->get_list_type_node();
        $string_data = gui_form_select_field("type_update", "type_update", $dataService, $data[0][2], false, "", 0);

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"type\">" . Strings::LABEL_0057 . "</label>");
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        echo gui_table_tag_close();

        echo gui_form_post_close();

        // Delete form

        echo gui_form_post_open("corporate_delete", RenderUrl('nodes/delete?node=list'));
        echo gui_form_input_hidden_field("id_noeud", $data[0][0]);
        echo gui_form_post_close();
    }

    public function show_form_corporate() {
        GLOBAL $LABEL_0060, $LABEL_0061;

        echo gui_form_post_open("corporate_creation", RenderUrl('nodes/create?node=list'));

        echo gui_table_tag_open("100%", 0, 5, 0, NULL, NULL, NULL);

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"noeud_parent\">" . $LABEL_0061 . "</label>");
        $dataNode = $this->get_list_node();
        $tabTmp = array(0, Strings::LABEL_0062);
        array_unshift($dataNode, $tabTmp);
        $string_data = gui_form_select_field("noeud_parent", "noeud_parent", $dataNode, "", false, "", 0);
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"designation\">" . $LABEL_0060 . "</label>");
        $string_data = gui_form_input_text_field("designation", "", 50, 255, "", true, false);
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        echo gui_tr_tag_open();
        echo gui_td_tag("<label for=\"type\">" . Strings::LABEL_0057 . "</label>");
        $dataService = $this->get_list_type_node();
        $string_data = gui_form_select_field("type", "type", $dataService, "", false, "", 0);
        echo gui_td_tag($string_data);
        echo gui_tr_tag_close();

        echo gui_table_tag_close();

        //echo "\n<small><button type=\"submit\" onclick=\"/*load_img();*/\">" . Strings::LABEL_0025 . "</button></small>";
        echo gui_form_post_close();
    }

    //============================================================================
    // show_corporate_tree()
    // Attention fonction récursive qui exploite les tableaux de l'objet pour ne 
    // pas solliciter la BDD 
    // L'encapsulation des tableaux peut être modifié pour changer l'esthétique de 
    // l'arborescence
    //============================================================================
    public function show_corporate_tree($id_node_parent = 0, $num = 0) {
        GLOBAL $ICON_UPDATE, $ICON_DELETE, $DISPLAY_UPDATE, $REQUEST_042;

        $query = <<<SQL
SELECT D.id, D.text, D.type, D.node
FROM (
    SELECT A.id_noeud AS id,A.designation AS text,A.type,B.designation AS node
    FROM adm_client_arborescence AS A
    LEFT JOIN adm_type_noeud AS B ON A.type=B.type_noeud
    WHERE A.id_parent=:parent
UNION
    SELECT NULL AS id, CONCAT(C.nom, ' ', C.prenom) AS text, 0 AS type, fonction AS node
    FROM adm_utilisateur AS C
    WHERE C.id_noeud=:parent
) AS D ORDER BY D.type, D.text
SQL;

        $siblings_nodes = db_request_select($query, [':parent' => $id_node_parent], $this->db_name);

        if (count($siblings_nodes) === 1) {
            return $num;
        }

        echo "<table class=\"nodes\" cellpadding=\"0\" cellspacing=\"0\"  border=\"0\">";
        echo '<tr><td align="center">';

        foreach ($siblings_nodes as $sibling) {

            if ($sibling === FALSE) {
                break;
            }

            if ($sibling['type'] != 0) {
                continue;
            }

            echo "<div class=\"node node-shape-" . $sibling['type'] . "\">";
            echo "<big>" . $sibling['text'] . "</big>";
            echo "<br>" . $sibling['node'];
            echo "</div><br>";
        }

        echo "</td></tr>";
        echo "</table>";

        echo "<table class=\"nodes\" cellpadding=\"0\" cellspacing=\"0\"  border=\"0\"><tr>";

        foreach ($siblings_nodes as $sibling) {

            if ($sibling === FALSE) {
                break;
            }

            if ($sibling['type'] == 0) {
                continue;
            }

            echo '<td align="center">';

            echo "<div class=\"node node-shape-" . $sibling['type'] . "\" onclick=\"$('#dialog_update_node').data({base:'" . BASE_WWW . "',id:{$sibling['id']},db:'$this->db_name'}).dialog('open');\">";
            echo "<big>" . $sibling['text'] . "</big>";
            echo "<br>" . $sibling['node'];
            echo "</div>";

            $num = $this->show_corporate_tree($sibling['id'], ++$num);

            echo "</td>";
        }

        echo "</tr></table>";

        return $num++;
    }

}
